package cn.e4j.modular.crm.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.common.exception.BizExceptionEnum;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.PageReData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.FileUtil;
import cn.e4j.core.util.LangUtils;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.crm.service.GwamTService;
import cn.e4j.modular.utils.CrmExceptionEnum;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品资料维护管理
 * Created by shixc on 2019-1-11.
 */
@Controller
@RequestMapping("/crm/gwai500")
public class Gwai500Controller extends BaseController {

    @Autowired
    private GwamTService gwamTService;

    /**
     * 跳转产品资料管理页面
     */
    @RequiresPermissions("crm:gwai500:init")
    @RequestMapping(value = {"", "init"})
    public String index() {
        return "/pc/crm/gwai500.html";
    }

    /**
     * 查询产品资料信息列表
     */
    @RequestMapping("/getList")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData getList(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        List<Map<String, Object>> result = gwamTService.getList(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 查询产品属性特征值列表
     */
    @RequestMapping("/getGwanList")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData getGwanList(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        inDto.put("GWANENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> result = gwamTService.getGwanList(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 新增
     */
    @RequestMapping("/addGwam")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData addGwam(GwamT gwamT, GwamlT gwamlT, @DtoParam DtoWapper dtoWapper) {
        ShiroUser user = ShiroKit.getUser();
        Dto inDto = dtoWapper.getDto();
        gwamT.setGWAM014(inDto.getString("GWAM014"));
        gwamT.setGWAM016(inDto.getString("GWAM016"));
        gwamT.setGWAM016(inDto.getString("GWAM016"));
        gwamT.setGWAM017(inDto.getString("GWAM017"));
        gwamlT.setGWAML003(inDto.getString("GWAML003"));
        gwamlT.setGWAML004(inDto.getString("GWAML004"));
        gwamlT.setGWAML005(inDto.getString("GWAML005"));
        // 判断产品编号是否重复
        GwamT gwam = gwamTService.getByKey(user.getDBC(), gwamT.getGWAM001());
        if (gwam != null) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_CODE.getCode(),
                    CrmExceptionEnum.EXISTED_THE_CODE.getMessage());
        }
        gwamT.setGWAMENT(user.getDBC());
        gwamlT.setGWAMLENT(user.getDBC());
        gwamlT.setGWAML001(gwamT.getGWAM001());
        gwamlT.setGWAML002(LangUtils.getLang(user.getLANG()));
        if (gwamlT.getGWAML003() == null) {
            gwamlT.setGWAML003(" ");
        }
        if (gwamlT.getGWAML004() == null) {
            gwamlT.setGWAML004(" ");
        }
        if (gwamlT.getGWAML005() == null) {
            gwamlT.setGWAML005(" ");
        }
        gwamTService.addGwam(gwamT, gwamlT);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping("/editGwam")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData editGwam(GwamT gwamT, GwamlT gwamlT, @DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        gwamT.setGWAM014(inDto.getString("GWAM014"));
        gwamT.setGWAM015(inDto.getString("GWAM015"));
        gwamT.setGWAM016(inDto.getString("GWAM016"));
        gwamT.setGWAM017(inDto.getString("GWAM017"));
        gwamlT.setGWAML003(inDto.getString("GWAML003"));
        gwamlT.setGWAML004(inDto.getString("GWAML004"));
        gwamlT.setGWAML005(inDto.getString("GWAML005"));
        gwamTService.editGwam(gwamT, gwamlT);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping("/delGwam")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData delGwam(GwamT gwamT, GwamlT gwamlT) {
        gwamTService.deleteGwam(gwamT, gwamlT);
        return SUCCESS_TIP;
    }

    /**
     * 批量删除数据
     */
    @RequestMapping("/deleteDataBatchGwam")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData deleteDataBatchGwam(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwamT> gwajTList = inDto.getReqList(GwamT.class);
        gwamTService.delDataBatchGwam(gwajTList);
        return SUCCESS_TIP;
    }

    /**
     * 获取产品分类列表
     */
    @ResponseBody
    @RequestMapping("/getGwahList")
    public Dto getGwahList(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        inDto.put("GWAHENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> list = gwamTService.getGwahList(inDto);
        outDto.put("list", list);
        return outDto;
    }

    /**
     * 获取产品分类列表
     */
    @ResponseBody
    @RequestMapping("/getGwaoList")
    public Dto getGwaoList(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        inDto.put("GWAOENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> list = gwamTService.getGwaoList(inDto);
        outDto.put("list", list);
        return outDto;
    }

    /**
     * 获取产品分类列表
     */
    @ResponseBody
    @RequestMapping("/getGwabList")
    public Dto getGwabList(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        inDto.put("GWABENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> list = gwamTService.getGwabList(inDto);
        outDto.put("list", list);
        return outDto;
    }

    /**
     * 获取属性特征分类列表
     */
    @ResponseBody
    @RequestMapping("/getGwaiList")
    public Dto getGwaiList(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        inDto.put("GWAIENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> list = gwamTService.getGwaiList(inDto);
        outDto.put("list", list);
        return outDto;
    }

    /**
     * 获取属性特征值列表
     */
    @ResponseBody
    @RequestMapping("/getGwajList")
    public Dto getGwajList(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto outDto = Dtos.newDto();
        ShiroUser shiroUser = ShiroKit.getUser();
        inDto.put("GWAJENT", shiroUser.getDBC());
        inDto.put("lang", LangUtils.getLang(shiroUser.getLANG()));
        List<Map<String, Object>> list = gwamTService.getGwajList(inDto);
        outDto.put("list", list);
        return outDto;
    }

    /**
     * 新增
     */
    @RequestMapping("/addGwan")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData addGwan(GwanT gwanT) {
        ShiroUser user = ShiroKit.getUser();
        // 判断产品编号是否重复
        GwanT gwan = gwamTService.getByGwan(user.getDBC(), gwanT.getGWAN001(), gwanT.getGWAN002());
        if (gwan != null) {
            return new ErrorResponseData(CrmExceptionEnum.EXISTED_THE_CODE.getCode(),
                    CrmExceptionEnum.EXISTED_THE_CODE.getMessage());
        }
        gwamTService.addGwan(gwanT);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping("/editGwan")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData editGwan(GwanT gwanT) {
        gwamTService.editGwan(gwanT);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping("/delGwan")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData delGwan(GwanT gwanT) {
        gwamTService.deleteGwan(gwanT);
        return SUCCESS_TIP;
    }

    /**
     * 批量删除数据
     */
    @RequestMapping("/deleteDataBatchGwan")
    @RequiresPermissions("crm:gwai500:init")
    @ResponseBody
    public ResponseData deleteDataBatchGwan(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwanT> gwanTList = inDto.getReqList(GwanT.class);
        gwamTService.delDataBatchGwan(gwanTList);
        return SUCCESS_TIP;
    }

    /**
     * 查询仓库资料信息列表
     */
    @RequestMapping("/getGwasList")
    @ResponseBody
    public ResponseData getGwasList(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        List<Map<String, Object>> result = gwamTService.getGwasList(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 查询最新产品信息
     */
    @RequestMapping("/getProductList")
    @ResponseBody
    public ResponseData getProductList(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<Dto> result = gwamTService.getProductList(inDto);
        return ResponseData.success(result);
    }


    /**
     * 产品资料上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/imgs")
    @ResponseBody
    public ResponseData imgs(HttpServletRequest request) {
        List<Map<String, String>> paths;
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        try {
            paths = saveFiles(files, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.UPLOAD_ERROR.getMessage());
        }
        return new SuccessResponseData(paths);
    }

    /**
     * 保存产品资料的上传图片
     *
     * @param files
     * @param basePath
     * @return
     * @throws IOException
     */
    public List<Map<String, String>> saveFiles(List<MultipartFile> files, String basePath) throws IOException {
        List<Map<String, String>> paths = new ArrayList<>();
        for (MultipartFile file : files) {
            Map<String, String> map = new HashMap<>();
            String name = file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf("."));
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
            Dto dto = Dtos.newDto();
            dto.put("NAME", name);
            Dto pDto = gwamTService.getPicture(dto);
            if (pDto.getString("COUNT").equals("0")) {
                map.put("name", name + "." + type);
            } else {
                map.put("name", name + "-" + pDto.getString("COUNT") + "." + type);
            }
            if (basePath != null) {
                map.put("path", basePath + "/");
                FileUtil.createFolder(map.get("path"), false);
            } else {
                map.put("path", "");
            }

            File newFile = new File(map.get("path") + map.get("name"));
            file.transferTo(newFile);
            paths.add(map);
        }
        return paths;
    }

    @RequestMapping(value = "/exportsData", method = RequestMethod.GET)
    @RequiresPermissions("crm:gwai500:init")
    public void exportsData(ModelMap map, HttpServletRequest request, HttpServletResponse response, @DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwamExport> list = gwamTService.getListExport(inDto);
        ExportParams params = new ExportParams(null, "产品资料数据", ExcelType.XSSF);
        //params.setFreezeCol(2);
        map.put(NormalExcelConstants.FILE_NAME, "产品资料数据");
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put(NormalExcelConstants.CLASS, GwamExport.class);
        map.put(NormalExcelConstants.PARAMS, params);
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }
}
